<template>
  <div class="relation-details-page app-container">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="submitHandle()" label-width="180px">
      <el-form-item prop="investChildrenName" label="子投资名称：">
        <el-input v-model="dataForm.investChildrenName" placeholder="请输入子投资名称" style="width: 360px;"></el-input>
      </el-form-item>
      <el-form-item prop="strategyName" label="关联策略：">
        <el-input v-model="dataForm.strategyName" placeholder="请选择关联策略" readonly style="width: 360px;">
          <el-button slot="append" icon="el-icon-search" @click="selectHandle"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item v-if="!dataForm.accountList.length" prop="initEquity" label="初始权益(万元)：">
        <el-input-number v-model="dataForm.initEquity" @change="initialMoneyChangeTop" :precision="2" placeholder="请输入初始权益" style="width: 160px;" :controls="false"></el-input-number>
      </el-form-item> 
      <el-form-item v-if="!dataForm.accountList.length" label="初始份额 / 单位净值：">
        <el-input-number v-model="dataForm.initShare" @change="initialShareChangeTop" :precision="2" placeholder="请输入初始份额" style="width: 160px;" :controls="false"></el-input-number>
        <el-input-number v-model="dataForm.initNetWorth" @change="initialNetworthChangeTop" :precision="4" placeholder="请输入单位净值" style="width: 160px;margin-left: 40px;" :controls="false"></el-input-number>
      </el-form-item>
      <el-form-item prop="investIndex" label="对标指数：">
        <indexSelectTree :multiple="false" :width="360" v-model="dataForm.investIndex" @contrastOptionsObj="contrastOptionsObjHandle"></indexSelectTree>
      </el-form-item>
      <el-form-item prop="investStatus" label="投资状态：">
        <el-select v-model="dataForm.investStatus" placeholder="请选择投资状态" style="width: 360px;">
          <el-option :label="item.name" :value="item.id" v-for="item in investStatusList" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <div>
        <el-button type="danger" size="small" style="margin: 0 0 22px 66px;" @click="addHandle">添加融航子账号</el-button>
        <span class="tip">* 配置后，将自动同步融航子账号操盘净值数据。</span>
      </div>
      <div class="card" v-for="(item, i) in dataForm.accountList" :key="item.id">
        <div class="card-tit">
          <span>账号{{i+1}}：</span>
          <span v-if="item.canClose" class="close" @click="closeCardHandle(i)">X</span>
        </div>
        <el-form-item :prop="`accountList.${i}.investAccount`" label="操作账号：" :rules="dataRule.investAccount">
          <el-input v-model="item.investAccount" placeholder="请输入操作账号" style="width: 360px;"></el-input>
        </el-form-item>
        <el-form-item :prop="`accountList.${i}.initialMoney`" label="初始权益(万元)：" :rules="dataRule.initialMoney">
          <el-input-number v-model="item.initialMoney" @change="initialMoneyChange($event, i)" :precision="2" placeholder="请输入初始权益" style="width: 160px;" :controls="false"></el-input-number>
        </el-form-item> 
        <el-form-item prop="initialShare" label="初始份额 / 单位净值：">
          <el-input-number v-model="item.initialShare" @change="initialShareChange($event, i)" :precision="2" placeholder="请输入初始份额" style="width: 160px;" :controls="false"></el-input-number>
          <el-input-number v-model="item.initialNetworth" @change="initialNetworthChange($event, i)" :precision="4" placeholder="请输入单位净值" style="width: 160px;margin-left: 40px;" :controls="false"></el-input-number>
        </el-form-item>
        <!-- <el-form-item v-if="_strategyId" prop="investStarttime" label="投资开始时间："> -->
        <el-form-item prop="investStarttime" label="投资开始时间：">
          <el-date-picker
            v-model="item.investStarttime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            style="width: 360px;">
          </el-date-picker>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <el-button style="width: 220px;" type="primary" @click="addSubmitHandle">保存</el-button>
    </div>
    
    <strategyOpen v-if="addOrUpdateVisible" ref="addOrUpdate" :userId="userId" @selctInvestName="selctInvestNameHandle"></strategyOpen>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { insertDetail, queryInvestDetailById } from '@/api/afterInvest' // updateDetail
import indexSelectTree from '@/components/investComn/indexSelectTree.vue'
import strategyOpen from '@/views/afterManage/afterInvest/relation/strategyOpen.vue'

export default {
  name: 'AfterInvestRelationDel',
  components: { indexSelectTree, strategyOpen },
  data() {
    var investIndexRule = (rule, value, callback) => {
      if(!value) {
        callback(new Error('请选择对标指数'))
      }else {
        callback()
      }
    }
    return {
      _strategyId: '',
      investAccount: '',
      investAdviser: '',
      contrastOptions_obj: {},
      investStatusList: [
        { id: 0, name: '未开始' },
        { id: 1, name: '进行中' },
        { id: 2, name: '已终止' },
      ],
      dataForm: {
        investId: '',
        strategyId: '',
        strategyName: '',
        investIndex: undefined,
        investIndexText: '',
        investStatus: 0,
        initEquity: undefined,
        initShare: undefined,
        initNetWorth: undefined,
        accountList: []
      },
      addOrUpdateVisible: false,
      dataRule: {
        investChildrenName: [{ required: true, message: '请输入子投资名称', trigger: 'change' }],
        investIndex: [{ validator: investIndexRule, required: true, trigger: 'change' }],
        investAccount: [{ required: true, message: '请输入操作账户', trigger: 'blur' }],
        initialMoney: [{ required: true, message: '请输入初始权益', trigger: 'blur' }],
        initEquity: [{ required: true, message: '请输入初始权益', trigger: 'blur' }],
        investStarttime: [{ required: true, message: '请输入投资开始时间', trigger: 'blur' }],
      }
    }
  }, 
  computed: {
    ...mapGetters(['userId']),
  },
  created() {
    this.dataForm.investId = this.$route.query.id
    this.dataForm.investIndex = Number(this.$route.query.investIndex)
    this._strategyId = this.$route.query.strategyId
    this.investAccount = this.$route.query.investAccount
    this.investAdviser = this.$route.query.investAdviser
    if(this._strategyId) this.queryInvestDetailById(this._strategyId)
  },
  methods: {
    closeCardHandle(i) {
      this.dataForm.accountList.splice(i, 1)
      // if(this.dataForm.accountList.length>1) {
      //   this.dataForm.accountList.splice(i, 1)
      // }else {
      //   this.$notify({
      //     type: 'warning',
      //     message: '至少添加一个操作账号',
      //     duration: 2000
      //   })
      // }
    },
    addHandle() {
      this.dataForm.initEquity = undefined
      this.dataForm.initNetWorth = undefined
      this.dataForm.initShare = undefined
      this.dataForm.accountList.push({
        canClose: true,
        id: new Date().getTime(),
        investAccount: '',
        initialMoney: undefined,
        initialShare: undefined,
        initialNetworth: undefined,
        investStarttime: undefined
      })
    },
    initialMoneyChangeTop(val) {
      if(this.dataForm.initNetWorth) {
        this.dataForm.initNetWorth = (val*10000/this.dataForm.initShare).toFixed(4)
      }else {
        this.dataForm.initNetWorth = 1
        this.dataForm.initShare = val*10000
      }
    },
    initialShareChangeTop(val) {
      if(this.dataForm.initEquity) this.dataForm.initNetWorth = (this.dataForm.initEquity*10000/val).toFixed(4)
    },
    initialNetworthChangeTop(val) {
      if(this.dataForm.initEquity) this.dataForm.initShare = (this.dataForm.initEquity*10000/val).toFixed(4)
    },
    initialMoneyChange(val, i) {
      if(this.dataForm.accountList[i].initialNetworth) {
        this.dataForm.accountList[i].initialNetworth = (val*10000/this.dataForm.accountList[i].initialShare).toFixed(4)
      }else {
        this.dataForm.accountList[i].initialNetworth = 1
        this.dataForm.accountList[i].initialShare = val*10000
      }
    },
    initialShareChange(val, i) {
      if(this.dataForm.accountList[i].initialMoney) this.dataForm.accountList[i].initialNetworth = (this.dataForm.accountList[i].initialMoney*10000/val).toFixed(4)
    },
    initialNetworthChange(val, i) {
      if(this.dataForm.accountList[i].initialMoney) this.dataForm.accountList[i].initialShare = (this.dataForm.accountList[i].initialMoney*10000/val).toFixed(4)
    },
    contrastOptionsObjHandle(obj) {
      this.contrastOptions_obj = obj
    },
    selctInvestNameHandle(strategyInfoVo) {
      this.dataForm.strategyId = strategyInfoVo.strategyId
      this.dataForm.strategyName = strategyInfoVo.strategyName
    },
    selectHandle() {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init()
      })
    },
    queryInvestDetailById(id) {
      queryInvestDetailById({ id }).then(res => {
        this.dataForm = res.body
      })
    },
    addSubmitHandle() {
      this.$refs['dataForm'].validate((valid) => {
        if(valid) {
          this.dataForm.investIndexText = this.contrastOptions_obj[this.dataForm.investIndex]
          this.dataForm.accountList.map(item => {
            item.initialMoney = (item.initialMoney).toFixed(4)
            item.initialNetworth = (item.initialNetworth).toFixed(4)
            item.initialShare = (item.initialShare).toFixed(4)
          })
          insertDetail({
            createdby: this.userId,
            ...this.dataForm
          }).then(res => {
            this.$notify({
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.$store.dispatch("tagsView/delView", this.$route)
            this.$router.push({
              path: '/afterManage/afterInvest/relation',
              query: {
                id: this.dataForm.investId,
                investAccount: this.investAccount, 
                investAdviser: this.investAdviser,
                investIndex: this.dataForm.investIndex,
                refresh: new Date().getTime()
              }
            })
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.relation-details-page {
  .tip {
    padding-left: 15px;
    font-size: 12px;
    color: #f30;
  }
  .card {
    border: 1px solid #ddd;
    & + .card { margin-top: 22px; }
  }
  .card-tit {
    display: flex;
    justify-content: space-between;
    align-items: center;
    line-height: 34px;
    background: #eee;
    padding: 0 12px;
    font-weight: bold;
    margin-bottom: 22px;
    .close {
      width: 20px;
      line-height: 20px;
      text-align: center;
      background: #ff3300;
      color: #fff;
      border-radius: 50%;
      cursor: pointer;
    }
  }
  .addNetworth {
    border: 1px solid #ddd;
    margin-top: 20px;
    padding-bottom: 22px;
    .addNetworth-line {
      padding: 0 16px;
      .el-icon-close {
        cursor: pointer;
        color: #ff561b;
        font-weight: bold;
        font-size: 16px;
        margin-left: 20px;
      }
      .el-icon-plus {
        cursor: pointer;
        color: #409EFF;
        font-weight: bold;
        font-size: 16px;
        margin-left: 10px;
      }
    }
    .addNetworth-line + .addNetworth-line {
      margin-top: 12px;
    }
  }
  .footer {
    margin-top: 40px;
    text-align: center;
  }
}
</style>

